package com.shfl.Controller;

import java.io.File;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;

import com.shfl.Util.ExcelUtil;
import com.shfl.Util.MapObjUtil;
import com.shfl.app.One;
import com.shfl.app.Second;
import com.shfl.app.Three;
import com.shfl.model.UserInfo;
import com.shfl.model.WokingLog;
import com.shfl.model.WokingTime;
import com.shfl.stock.Stock;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.Window;

@SuppressWarnings("rawtypes")
public class ThreeController implements Initializable {

	@FXML
	private Button selestFile;

	@FXML
	private TextField selectPath;

	@FXML
	private TableView tview;

	@FXML
	private TableColumn userNo;

	@FXML
	private TableColumn username;

	@FXML
	private TableColumn inTimem;

	@FXML
	private TableColumn primarySector;

	@FXML
	private TableColumn secondarySector;

	@FXML
	private TableColumn jobDescription;

	@FXML
	private TableColumn lateCount;

	@FXML
	private TableColumn lateDateList;

	@FXML
	private TableColumn LeaveEarly;

	@FXML
	private TableColumn LeaveEarlyList;

	@FXML
	private TableColumn absenteeismCount;

	@FXML
	private TableColumn absenteeismList;

	@FXML
	private Button selectButton;// 查询

	@FXML
	private Button selectExport;// 导出

	@FXML
	private TextField selectExportInput;// 按钮

	@FXML
	private TextField selectInput;

	@FXML
	private TextArea noInfo;
	
	@FXML
	private Button breakOne;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		StringBuffer sb = new StringBuffer();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
		Stock.USER_WORKING_LOG.forEach((k, v) -> {
			if(!Stock.FALG){
				return ;
			}
			if (Stock.USER_INFO.containsKey(k)) {
				UserInfo userInfo = Stock.USER_INFO.get(k);
				Long userStratTime = 0L;
				Long userEndTime = 0L;
				for (WokingLog wokingLog : v) {
					if (null == wokingLog.getClockIn() || null == wokingLog.getClockOut()
							|| wokingLog.getClockIn().isEmpty() || wokingLog.getClockOut().isEmpty()) {
						userInfo.setAbsenteeismCount(userInfo.getAbsenteeismCount() + 1);
						List<String> absenteeismList = userInfo.getAbsenteeismList();
						absenteeismList.add(wokingLog.getWorkingDate().toString());
						continue;
					}
					try {
						userStratTime = simpleDateFormat.parse(wokingLog.getClockIn()).getTime();
						userEndTime = simpleDateFormat.parse(wokingLog.getClockOut()).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}

					// 存在早晚班
					if (Stock.JOB_TIME_MAP.containsKey(userInfo.getJobDescription())) {
						WokingTime wokingTime = Stock.JOB_TIME_MAP.get(userInfo.getJobDescription());
						String clockOut = wokingLog.getClockOut();
						if (clockOut.startsWith("00") || clockOut.startsWith("01")) {
							Optional<WokingTime> wokingTimeOp = Stock.JOB_TIME_LIST.stream()
									.filter(s -> s.getNightEndTime().startsWith("00")).findFirst();
							if (wokingTimeOp.isPresent()) {
								wokingTime = wokingTimeOp.get();
							}
						} else {
							Optional<WokingTime> wokingTimeOp = Stock.JOB_TIME_LIST.stream()
									.filter(s -> !s.getNightEndTime().startsWith("00")).findFirst();
							if (wokingTimeOp.isPresent()) {
								wokingTime = wokingTimeOp.get();
							}
						}
						try {
							// 早班
							if (userStratTime < 10800000) {
								if (userStratTime > simpleDateFormat.parse(wokingTime.getEarlyStartTime()).getTime()) {
									// 迟到
									userInfo.setLateCount(userInfo.getLateCount() + 1);
									List<String> lateDateList = userInfo.getLateDateList();
									lateDateList.add(wokingLog.getWorkingDate().toString());
									userInfo.setLateDateList(lateDateList);
								}
								if (userEndTime < simpleDateFormat.parse(wokingTime.getEarlyEndTime()).getTime()) {
									// 早退
									userInfo.setLeaveEarly(userInfo.getLeaveEarly() + 1);
									List<String> leaveEarlyDateList = userInfo.getLeaveEarlyList();
									leaveEarlyDateList.add(wokingLog.getWorkingDate().toString());
									userInfo.setLeaveEarlyList(leaveEarlyDateList);
								}
							}
							// 晚班
							else {
								if (userStratTime > simpleDateFormat.parse(wokingTime.getNightStartTime()).getTime()) {
									// 迟到
									userInfo.setLateCount(userInfo.getLateCount() + 1);
									List<String> lateDateList = userInfo.getLateDateList();
									lateDateList.add(wokingLog.getWorkingDate().toString());
									userInfo.setLateDateList(lateDateList);

								}
								if (userEndTime < simpleDateFormat.parse(wokingTime.getNightEndTime()).getTime()) {
									// 早退
									userInfo.setLeaveEarly(userInfo.getLeaveEarly() + 1);
									List<String> leaveEarlyDateList = userInfo.getLeaveEarlyList();
									leaveEarlyDateList.add(wokingLog.getWorkingDate().toString());
									userInfo.setLeaveEarlyList(leaveEarlyDateList);
								}
							}

						} catch (ParseException e) {
							e.printStackTrace();
						}

					}
					// 默认时间
					else {
						try {
							if (userStratTime > simpleDateFormat.parse(Stock.DEFAULT_WOKING_TIME.getStartTime())
									.getTime()) {
								// 迟到
								userInfo.setLateCount(userInfo.getLateCount() + 1);
								List<String> lateDateList = userInfo.getLateDateList();
								lateDateList.add(wokingLog.getWorkingDate().toString());
								userInfo.setLateDateList(lateDateList);
							}
							if (userEndTime < simpleDateFormat.parse(Stock.DEFAULT_WOKING_TIME.getEndTime())
									.getTime()) {
								// 早退
								userInfo.setLeaveEarly(userInfo.getLeaveEarly() + 1);
								List<String> leaveEarlyDateList = userInfo.getLeaveEarlyList();
								leaveEarlyDateList.add(wokingLog.getWorkingDate().toString());
								userInfo.setLeaveEarlyList(leaveEarlyDateList);
							}
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}

			} else {
				sb.append(k + ",");
			}
		});
		insertTableView();
		this.noInfo.setText(sb.toString());
		// 查询
		this.selectButton.setOnAction(event -> {
			List<UserInfo> userInfoTempList = new LinkedList<UserInfo>();

			List<UserInfo> userInfoList = new LinkedList<UserInfo>();
			getTableView(userInfoList);
			String userName = this.selectInput.getText() != null ? this.selectInput.getText() : "";
			if (userName.trim().isEmpty()) {
				insertTableView();
			} else {
				Stock.USER_INFO.forEach((k, v) -> {
					userInfoList.add(v);
				});
				Optional<UserInfo> userInfoOp = userInfoList.stream()
						.filter(s -> s.getUsername().equals(userName.trim())).findFirst();
				if (userInfoOp.isPresent()) {
					userInfoTempList.add(userInfoOp.get());
					getTableView(userInfoTempList);
				}
			}
		});

		// 选择导出路径
		this.selectExport.setOnAction(event -> {
			if(!Stock.FALG){
				return ;
			}
			List<Map<String, Object>> tempList = new LinkedList<Map<String, Object>>();
			List<UserInfo> userInfoList = new LinkedList<UserInfo>();
			getTableView(userInfoList);
			String userName = this.selectInput.getText();
			if (userName.trim().isEmpty()) {
				Stock.USER_INFO.forEach((k, v) -> {
					tempList.add(MapObjUtil.object2Map(v));
				});
			} else {
				Stock.USER_INFO.forEach((k, v) -> {
					userInfoList.add(v);
				});

				Optional<UserInfo> userInfoOp = userInfoList.stream()
						.filter(s -> s.getUsername().equals(userName.trim())).findFirst();
				if (userInfoOp.isPresent()) {
					tempList.add(MapObjUtil.object2Map(userInfoOp.get()));
				}
			}

			DirectoryChooser chooser = new DirectoryChooser();
			Window window = ((Node) event.getSource()).getScene().getWindow();
			File file = chooser.showDialog(window);
			if (file != null && file.exists() && file.isDirectory()) {
				this.selectExportInput.setText(file.getAbsolutePath());
				// List dataKey
				String[] dataKeyArry = { "userNo", "username", "inTimem", "primarySector", "secondarySector",
						"jobDescription", "lateCount", "lateDateList", "LeaveEarly", "LeaveEarlyList",
						"absenteeismCount", "absenteeismList" };
				// List dataTitle
				String[] dataTitleArry = { "编号", "姓名", "入职时间", "一级部门", "二级部门", "职位描述", "迟到次数", "迟到日期", "早退次数", "早退日期",
						"缺勤次数", "缺勤日期" };
				Stock.SECOND_STAG_DIALOG.activateProgressBar();
				// 生成Excel
				try {
					ExcelUtil.buildExcel(file.getAbsolutePath(), Arrays.asList(dataKeyArry),
							Arrays.asList(dataTitleArry), tempList, "员工考勤结果");
				} catch (Exception e) {
				}finally{
					Stock.SECOND_STAG_DIALOG.cancelProgressBar();
				}
				
				insertTableView();
			}

		});
		
		this.breakOne.setOnAction(event -> {
			try {
				breakWindow();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});

	}

	public void insertUserWorking(List<String[]> list) {
	}

	public void insertTableView() {
		List<UserInfo> userInfoList = new LinkedList<UserInfo>();
		Stock.USER_INFO.forEach((k, v) -> {
			userInfoList.add(v);
		});
		getTableView(userInfoList);
	}

	@SuppressWarnings({ "unchecked" })
	public void getTableView(List<UserInfo> userInfoList) {
		ObservableList<UserInfo> list = FXCollections.observableArrayList();
		userNo.setCellValueFactory(new PropertyValueFactory("userNo"));

		username.setCellValueFactory(new PropertyValueFactory("username"));

		inTimem.setCellValueFactory(new PropertyValueFactory("inTimem"));

		primarySector.setCellValueFactory(new PropertyValueFactory("primarySector"));

		secondarySector.setCellValueFactory(new PropertyValueFactory("secondarySector"));

		jobDescription.setCellValueFactory(new PropertyValueFactory("jobDescription"));

		lateCount.setCellValueFactory(new PropertyValueFactory("lateCount"));

		lateDateList.setCellValueFactory(new PropertyValueFactory("lateDateList"));

		LeaveEarly.setCellValueFactory(new PropertyValueFactory("LeaveEarly"));

		LeaveEarlyList.setCellValueFactory(new PropertyValueFactory("LeaveEarlyList"));

		absenteeismCount.setCellValueFactory(new PropertyValueFactory("absenteeismCount"));

		absenteeismList.setCellValueFactory(new PropertyValueFactory("absenteeismList"));

		list.addAll(userInfoList);
		tview.setItems(list); // tableview添加list
	}

	public void insertWokingFinishing() {
	}
	public void breakWindow() throws Exception {
		Stock.THREE.stop();
		Stock.SECOND.showWindow();
	}
}
